package com.huluobo.a2209mdmdemo.views

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.TimeUtils
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMConversation
import com.hyphenate.chat.EMTextMessageBody
import kotlinx.coroutines.launch
import java.util.Date

/**
 *  Created by LC on 2025/2/24.
 */
@Composable
fun MessagePage(navHostController: NavHostController) {
    val list = remember {
        SnapshotStateList<EMConversation>()
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            list.addAll(EMClient.getInstance().chatManager().allConversations.values)
        }
    })

    Column(Modifier.padding(20.dp)) {
        LazyColumn(
            modifier = Modifier.fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(10.dp),
            content = {
                items(list) {
                    ConversationItem(emConversation = it, navHostController = navHostController)
                }
            })
    }
}

@Composable
fun ConversationItem(emConversation: EMConversation, navHostController: NavHostController) {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .padding(10.dp)
            .fillMaxWidth(),
    ) {
        Column(modifier = Modifier.height(40.dp), verticalArrangement = Arrangement.SpaceBetween) {
            Text(text = emConversation.conversationId())
            Text(text = (emConversation.lastMessage.body as EMTextMessageBody).message)
        }
        Text(text = TimeUtils.date2String(Date(emConversation.lastMessage.msgTime)))
    }
}